package com.greate.community.controller.master;

import com.alibaba.fastjson.JSON;
import com.greate.community.entity.User;
import com.greate.community.service.UserService;
import com.greate.community.service.master.LoginAdminService;
import com.greate.community.service.master.UserAdminService;
import com.greate.community.util.CommunityConstant;
import com.greate.community.util.CommunityUtil;
import com.greate.community.util.HostHolder;
import com.greate.community.util.RedisKeyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/loginAdmin")
public class LoginAdminController implements CommunityConstant {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    UserService userService;

    @Autowired
    LoginAdminService loginAdminService;

    @Autowired
    private HostHolder hostHolder;

    @Value("${server.servlet.context-path}")
    private String contextPath;
    /**
     * 用户登录
     * 这里应该重写逻辑 我偷了个懒 使用用户页面的登录
     * 什么身份都能登录  但在最后做了个判断 其是否为管理员
     * @return
     */
    @PostMapping("/login")
    public String login(@RequestBody  User user
                        ) {


        // 凭证过期时间（是否记住我）
        int expiredSeconds = REMEMBER_EXPIRED_SECONDS ;
        // 验证用户名和密码
        Map<String, Object> map = userService.login(user.getUsername(), user.getPassword(), expiredSeconds);
        if (map.containsKey("ticket")) {
            //账户密码均正确 判断是否为管理员
            boolean res=loginAdminService.isAdminUser(user.getUsername());
            if (res){//是管理员
                //拿到账户信息
                User userAdmin = userService.findUserByName(user.getUsername());
                System.out.println("user"+userAdmin);
                // 账号和密码均正确，则服务端会生成 ticket，浏览器通过 cookie 存储 ticket
                Cookie cookie = new Cookie("ticket", map.get("ticket").toString());
                cookie.setPath(contextPath); // cookie 有效范围
                cookie.setMaxAge(expiredSeconds);
                HashMap<String, Object> cookieInfo = new HashMap<>();
                cookieInfo.put("cookie",cookie);
                cookieInfo.put("userAdmin",userAdmin);
                return CommunityUtil.getJSONString(200,"",cookieInfo);
            }else {
                return CommunityUtil.getJSONString(401,"非管理员账号禁止登录");
            }

        }
        else {
            //返回错误信息
            return CommunityUtil.getJSONString(403,"账户或密码错误");
        }

    }

    /**
     * 用户登出
     * @param ticket 设置凭证状态为无效
     * @return
     */
    @GetMapping("/logout")
    public String logout(@CookieValue("ticket") String ticket) {
        userService.logout(ticket);
        SecurityContextHolder.clearContext();
        return CommunityUtil.getJSONString(200,"退出登录");
    }


}
